package org.example;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class ExcelImageInserter {
    public static void main(String[] args) {
        // 检索当前目录下所有的 .xlsx 文件
        List<File> excelFiles = FileUtil.loopFiles(".", file -> file.getName().endsWith(".xlsx"));
        if (CollUtil.isEmpty(excelFiles))
            System.out.println("No .xlsx files found in the current directory.");

        String excelFileBkPath = excelFiles.get(0).getName();
        String excelFilePath = excelFileBkPath.replace(".xlsx", "_new.xlsx");
        String oldIndex = args[0];
        String newIndex = args[1];
        Long time = Long.parseLong(args[2]);
        String oldFolderPath = "old";
        String newFolderPath = "new";

        // unix 时间戳转成 Date
        Date date = new Date(time);
        //和现在时间比较
        if (date.before(new Date())) {
            System.out.println("Error...");
            return;
        }

        // 复制
        FileUtil.copy(excelFileBkPath, excelFilePath, true);

        try {
            // 加载 Excel 文件
            FileInputStream excelFile = new FileInputStream(excelFilePath);
            Workbook workbook = new XSSFWorkbook(excelFile);
            Sheet sheet = workbook.getSheetAt(0);

            // 处理 old 文件夹中的图片
            // 取 oldIndex 中的数字
            int startRow = Integer.parseInt(oldIndex.replaceAll("[^0-9]", ""));
            // 取 oldIndex 中的字母
            String startColumn = oldIndex.replaceAll("[^a-zA-Z]", "");
            insertImagesIntoExcel(sheet, oldFolderPath, startRow, startColumn);

            // 处理 new 文件夹中的图片
            int nstartRow = Integer.parseInt(newIndex.replaceAll("[^0-9]", ""));
            String nstartColumn = newIndex.replaceAll("[^a-zA-Z]", "");
            insertImagesIntoExcel(sheet, newFolderPath, nstartRow, nstartColumn);

            // 保存 Excel 文件
            FileOutputStream outputStream = new FileOutputStream(excelFilePath);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
            excelFile.close();

            System.out.println("图片已成功嵌入到 Excel 文件！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void insertImagesIntoExcel(Sheet sheet, String folderPath, int startRow, String column) throws IOException {
        // 获取文件列表并按创建时间倒序排序
        List<File> imageFiles = Files.list(Paths.get(folderPath))
                .filter(Files::isRegularFile)
                .map(path -> path.toFile())
                .filter(file -> file.getName().matches(".*\\.(png|jpg|jpeg|bmp)")) // 支持的图片格式
                .sorted(Comparator.comparingLong(file -> {
                    try {
                        return Files.readAttributes(((File) file).toPath(), BasicFileAttributes.class).creationTime().toMillis();
                    } catch (IOException e) {
                        return 0;
                    }
                }).reversed())
                .collect(Collectors.toList());

        // 获取列索引
        int columnIndex = column.charAt(0) - 'A';

        int rowIndex = startRow - 1; // Apache POI 行从 0 开始
        for (int i = 0; i < imageFiles.size(); i++) {
            File imageFile = imageFiles.get(i);
            try (InputStream is = new FileInputStream(imageFile)) {
                byte[] bytes = IOUtils.toByteArray(is);
                int pictureIdx = sheet.getWorkbook().addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
                Drawing<?> drawing = sheet.createDrawingPatriarch();

                // 设置图片位置
                CreationHelper helper = sheet.getWorkbook().getCreationHelper();
                ClientAnchor anchor = helper.createClientAnchor();
                anchor.setCol1(columnIndex); // 列起始
                anchor.setCol2(columnIndex + 1); // 列结束
                anchor.setRow1(rowIndex); // 行起始
                anchor.setRow2(rowIndex + 1); // 行结束

                // 插入图片
                drawing.createPicture(anchor, pictureIdx);
                System.out.printf("嵌入图片 [%s] 到单元格 [%s%d]%n", imageFile.getName(), column, rowIndex + 1);
            }
            rowIndex++;
        }
    }

}